<?php
class Webadmin extends CI_Controller {

	public $m_strUser 		= "ชื่อผู้ใช้";
	public $m_strPass 		= "รหัสผ่าน";
	public $m_strRequired 	= "กรุณากรอกข้อมูล %s";
	public $m_strLoginError	= "ไม่สามารถเข้าสู่ระบบได้ โปรดติดต่อเจ้าหน้าที่";

	public function __construct()
	{
		parent::__construct();
		session_start();
	}

	public function index()
	{
		// already logged in
		if ( isset($_SESSION['username']) && isset($_SESSION['user_level']) )
		{
			redirect('welcome', 'refresh');
		}

		$this->load->library('form_validation');

		$frm = $this->form_validation;
		$frm->set_rules('user_login', $this->m_strUser, 'required|trim|max_length[20]');
		$frm->set_rules('user_password', $this->m_strPass, 'required|trim');
		$frm->set_message("required", $this->m_strRequired);

		if ($frm->run() == FALSE)
		{
			$data["err_msg"] = NULL;
			$this->load->view('webadmin', $data);
		}
		else
		{
			//form is OK.
			$this->load->model("user_model");
			$user = $this->input->post("user_login");
			$pass = $this->input->post("user_password");
			$res = $this->user_model->db_verify_user($user, $pass);
			if ($res != false)
			{
				//user has account
				$_SESSION['username'] = $user;
				$_SESSION['user_level'] = $res->level;
				//navigate to selection page
				redirect('welcome', 'refresh');
			}
			else
			{
				// unable to login
				$data["err_msg"] = $this->m_strLoginError;
				$this->load->view('webadmin', $data);
			}
		}
	}
	
	public function logout()
	{
		//echo "logout completed";
		session_destroy();
		redirect("webadmin", "refresh");
	}

}
?>
